package com.cskaoyan.user.service.impl;

import com.cskaoyan.user.constants.DBaffectedRows;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import com.cskaoyan.user.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserConverterMapper userConverter;

    @Override
    public UserLoginResponse login(UserLoginRequest userLogin) {

        Example example = new Example(Member.class);

        Example.Criteria criteria = example.createCriteria();
        String password = MD5Utils.encryptPassword(userLogin.getUserPwd(), userLogin.getUserName());
        criteria.andEqualTo("username",userLogin.getUserName())
                .andEqualTo("password",password).andEqualTo("isVerified","Y");

        List<Member> members = memberMapper.selectByExample(example);

        if (members.size()== DBaffectedRows.ONE){

            UserLoginResponse userLoginResponse = userConverter.converter(members.get(0));
            return userLoginResponse;
        }

        return null;
    }
}
